package org.lyxy.ssmdemo.controller;

import org.lyxy.ssmdemo.bean.User;
import org.lyxy.ssmdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    int startIndex = 0;
    int currentPage = 1;
    int pageSize = 5;

    /*
    * 登录功能
    * 登录成功：显示登录的用户名
    * 登录失败：回到登录页面
    */
    @RequestMapping("/login.do")
    public ModelAndView login(User user, HttpSession session){
        ModelAndView mv = new ModelAndView();

        User userResult = userService.findUser(user);
        List<User> users = userService.findUserByPage(startIndex, pageSize);

        if (userResult != null){
            mv.setViewName("forward:/index.jsp");
            session.setAttribute("user", userResult);
            int lastPage = userService.findCountPage(pageSize);

            mv.addObject("last", lastPage);

            mv.addObject("user", userResult);
            mv.addObject("users", users);
            mv.addObject("currentPage", currentPage);
            mv.addObject("information", "login success");
        }else {
            mv.setViewName("forward:/login.jsp");
            mv.addObject("information", "login fail");
        }

        return mv;
    }

    //页面数，分页查询
    @RequestMapping("/page.do")
    public ModelAndView page(int currentPage){
        ModelAndView mv = new ModelAndView();

        if(currentPage <= 0) {
            currentPage = 1;
        }
        //需要查询数据库 startIndex pageSize
        startIndex = (currentPage - 1) * pageSize;

        List<User> users = userService.findUserByPage(startIndex, pageSize);
        //尾页，总页数
        int lastPage = userService.findCountPage(pageSize);

        mv.addObject("last", lastPage);

        mv.addObject("users", users);
        mv.addObject("currentPage", currentPage);
        mv.setViewName("forward:/index.jsp");
        return mv;

    }

    @RequestMapping("/register.do")
    public ModelAndView register(User user, HttpServletResponse response) throws IOException {
        ModelAndView mv = new ModelAndView();
        int result = userService.addUser(user);
        if(result>0){
            mv.setViewName("forward:/login.jsp");
            mv.addObject("success","register success");
        }else{
            mv.setViewName("forward:/login.jsp");

            mv.addObject("success","register fail");
        }
        return mv;
    }

    @RequestMapping("/test.do")
    public ModelAndView test(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        mv.addObject("test", "跳转成功");
        return mv;
    }
}
